//
//  UIImage+Extension.m
//
//  Created by 👄 on 15/9/14.
//  Copyright (c) 2015年 sczy. All rights reserved.
//

#import "UIImage+Extension.h"

@implementation UIImage (Extension)

// 把image化圆
- (UIImage *)circleImage
{
    // NO代表透明
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
    
    // 获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 添加一个圆
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    
    // 方形变圆形
    CGContextAddEllipseInRect(ctx, rect);
    
    
    
    // 裁剪
    CGContextClip(ctx);
    
    // 将图片画上去
    [self drawInRect:rect];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

- (UIImage *)drawSquare
{
    CGFloat wh = MIN(self.size.width, self.size.height);
    CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, CGRectMake(0, 0, wh, wh));
    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
    UIGraphicsBeginImageContext(smallBounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, smallBounds, subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();
    return smallImage;
}

+(UIImage *)resizableImageName:(NSString *)imageName
{
    return [self resizableImage:[UIImage imageNamed:imageName]];
}

+(UIImage *)resizableImage:(UIImage *)image
{
    // 3个方法都可以指定拉伸某个位置
    //    [image stretchableImageWithLeftCapWidth:<#(NSInteger)#> topCapHeight:<#(NSInteger)#>];
    //
    //    [image resizableImageWithCapInsets:<#(UIEdgeInsets)#>];
    
    
    CGFloat imageW = image.size.width;
    CGFloat imageH = image.size.height;
    
    return [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageH * 0.5 - 1, imageW * 0.5 - 1, imageH * 0.5, imageW * 0.5) resizingMode:UIImageResizingModeStretch];
}

- (UIImage *)thumbnailWithSize:(CGSize)asize
{
    UIImage *newimage = nil;
    UIGraphicsBeginImageContext(asize);
    [self drawInRect:CGRectMake(0, 0, asize.width, asize.height)];
    newimage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimage;
}



-(UIImage *)imageResizeTo:(CGSize)newSize
{
    UIImage *img = [self copy];
    CGFloat scale = [[UIScreen mainScreen]scale];
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, scale);
    [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

//+(UIImage *)imageNamed_wl:(NSString *)imageName{
//    UIImage *img = nil;
//    img = [UIImage imageNamed:imageName];
//    if (!img) {
//        img = [UIImage yh_imageWithPDFFileNamed:imageName expectSize:CGSizeZero];
//    }
//    return img;
//}
@end
